' a function that complies with the TraverseDirectoryTree_CBK syntax
Function DisplayDirectoryName(ByVal path As String) As Boolean
Console.WriteLine(path)
If path = "C:\DOCS\LIBRI\OOP" Then Return True
End Function
' a delegate that defines the syntax of the function whose address
' can be passed to TraverseDirectoryTree - if this function returns True
' then the enumeration should be stopped
Delegate Function TraverseDirectoryTree_CBK(ByVal dirName As String) As Boolean
' a reusable procedure that traverse a directory tree and calls back the caller
' for each new directory
Sub TraverseDirectoryTree(ByVal path As String, ByVal callback As TraverseDirectoryTree_CBK)
Dim dirName As String
Static nestLevel As Integer ' nesting nestLevel
Static isCanceled As Boolean ' True if the client isCanceled the enumeration
nestLevel += 1
For Each dirName In System.IO.Directory.GetDirectories(path)
' call back the program to notify this directory
isCanceled = callback.Invoke(dirName)
If isCanceled Then Exit For
' call recursively this routine
TraverseDirectoryTree(dirName, callback)
Next
nestLevel -= 1
' reset isCanceled if we are about to return to the user
If nestLevel = 0 Then isCanceled = False
End Sub
Sub TestAPICallback()
EnumWindows(AddressOf EnumWindows_CBK, 0)
End Sub
End Module
' this module tests using callback delegates with Windows API calls
Module EnumWindowsDemo
Delegate Function EnumWindows_Callback(ByVal hWnd As Integer, ByVal lParam As Integer) As Integer
Public Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As EnumWindows_Callback, ByVal lParam As Integer) As Integer
Public Declare Function EnumChildWindows Lib "user32" (ByVal hWndParent As Integer, ByVal lpEnumFunc As EnumWindows_Callback, ByVal lParam As Integer) As Integer
Public Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As Integer, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer) As Integer
Public Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Integer, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
' The callback routine, common to both EnumWindows and EnumChildWindows.
' the argument passed in lParam is the indent level.
Function EnumWindows_CBK(ByVal hWnd As Integer, ByVal lParam As Integer) As Integer
' display information on this window, with correct indentation